package edu.ntu.im.p2ptrade.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.ntu.im.p2ptrade.LockManager;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.entity.ItemRepository;
import edu.ntu.im.p2ptrade.metadata.MetaData;
import edu.ntu.im.p2ptrade.metadata.MetaDataManager;

public class AddOrUpdateItem extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String sId = request.getParameter("id");
		String name = request.getParameter("name");
		String memo = request.getParameter("memo");
		String photoUrl = request.getParameter("url");
		boolean del = false;
		if ("T".equals(request.getParameter("del"))){
			del = true;
		}
				
		Item item = new Item(P2PTrade.getInstance().getPeerName(), name);
		if (sId != null && !"".equals(sId)) {
			item.setId(Integer.parseInt(sId));
		}
//		item.setName(name);
		item.setMemo(memo);
		item.setPhotoUrl(photoUrl);
//		item.setOwnerId(P2PTrade.getInstance().getPeerName());
		
		if (del == true){
			LockManager.getInstance().lockMySelf();
			ItemRepository.getInstance().deleteItem(item);
			LockManager.getInstance().unlockMySelf();
		}else if (sId!=null && !"".equals(sId)){
			ItemRepository.getInstance().updateItem(item);
			LockManager.getInstance().unlockMySelf();
		}else {
			ItemRepository.getInstance().addItem(item);
		}
		
		request.setAttribute("item", item);
		return mapping.findForward("success");
	}

}
